import { reactive, getCurrentInstance } from "vue";

export function useTopic({ props }) {
	const { emit } = getCurrentInstance()
	const useState = reactive({
		inputIds: [],
		inputArr: [],
		currentInputId: '',
		currentIdIndex: 0,
		answerResult: {},
		value: {}
	})
	// 存储input的索引
	const useSaveInputId = (index, i = 0, params = null) => {
		if(!params || (params && !params.value)) {
			useState.inputIds.push(`${index}${i}`)
			useState.inputArr.push([index, i])
		}
	}
	// 获取下一个索引
	const useGetNextId = (id) =>{
		if(!useState.currentInputId) {
			useState.currentInputId = useState.inputIds[0]
		}
		const idx = useState.inputIds.findIndex(item => item === (id || useState.currentInputId))
		useState.currentIdIndex = idx + 1
		useState.currentInputId = useState.inputIds[idx + 1]
	}
	// 选中当前
	const useSelectItem = (index, i) => {
		if(!props.isStart) { return }
		if(index === undefined && i === undefined) {
			useState.currentIdIndex = 0
			useState.currentInputId = useState.inputIds[0]
			return
		}
		const id = `${index}${i || 0}`
		const idx = useState.inputIds.findIndex(item => item === (id || useState.currentInputId))
		useState.currentIdIndex = idx
		useState.currentInputId = useState.inputIds[idx]
		// 外部函数
		props.parentCallback && props.parentCallback()
	}
	// 获取对象数据
	const setItemData = (value, conn) => {
		const ids = useState.inputArr[useState.currentIdIndex]
		// 一组单个填空
		const item = props.single ? props.data[ids[0]] : props.data[ids[0]][ids[1]]
		item.value = conn ? (item.value || '') + value : value
		return item.value
	}
	// 更新值
	const saveValue = (value) => {
		const ids = useState.inputArr[useState.currentIdIndex]
		if(!useState.value[ids[0]]) { useState.value[ids[0]] = [] }
		if(props.single) {
			useState.value[ids[0]] = value
		}else{
			useState.value[ids[0]][ids[1]] = value
		}
		emit('answer', useState.value)
	}
	// 选择结果
	const useChange = (value) => {
		const newValue = setItemData(value, true)
		// 保存值并返回
		saveValue(newValue)
	}
	// 撤回
	const useBack = () => {
		const ids = useState.inputArr[useState.currentIdIndex]
		let value = ''
		if(props.single) {
			value = useState.value?.[ids[0]] || ''
		}else{
			value = useState.value?.[ids[0]]?.[ids[1]] || ''
		}
		// 新值
		if(value.length) {
			value = value.substring(0, value.length - 1)
			const newValue = setItemData(value)
			// 保存值并返回
			saveValue(newValue)
		}
	}
	// 重写
	const useRewrite = () => {
		const newValue = setItemData('')
		// 保存值并返回
		saveValue(newValue)
	}
	// 保存结果
	const useSaveResult = (data) => {
		if(!useState.answerResult[data.index]) { useState.answerResult[data.index] = [] }
		const value = useState.answerResult[data.index]
		value[data.wordsIndex] = data.words
		useState.answerResult[data.index] = value
	}
	
	return {
		useState,
		useSaveInputId,
		useGetNextId,
		useSaveResult,
		useSelectItem,
		useChange,
		useBack,
		useRewrite
	}
}